#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>

// 模拟EBP3901的配置
#define SYSTEM_VERSION "1.0.0"
#define DEVICE_NAME "智能学习桌助手"

// 模拟调试输出
#define DEBUG_PRINT(level, format, ...)                           \
    do                                                            \
    {                                                             \
        if (level <= 2)                                           \
        {                                                         \
            printf("[%s] " format "\n",                           \
                   (level == 0) ? "ERROR" : (level == 1) ? "WARN" \
                                        : (level == 2)   ? "INFO" \
                                                         : "DEBUG", \
                   ##__VA_ARGS__);                                \
        }                                                         \
    } while (0)

// 系统状态
typedef enum
{
    STATE_IDLE,
    STATE_LISTENING,
    STATE_PROCESSING,
    STATE_SPEAKING,
    STATE_PRACTICE,
    STATE_ERROR
} system_state_t;

// 模拟硬件状态
static system_state_t current_state = STATE_IDLE;
static bool system_running = true;
static float simulated_distance = 40.0f; // 模拟距离
static bool voice_detected = false;
static bool led_on = false;
static bool buzzer_on = false;
static int posture_score = 100;

// 数据记录
typedef struct
{
    time_t timestamp;
    float distance;
    int posture_score;
    bool voice_detected;
    system_state_t state;
} data_record_t;

#define MAX_RECORDS 100
static data_record_t data_records[MAX_RECORDS];
static int record_index = 0;

// 函数声明
void signal_handler(int sig);
void simulator_init(void);
void simulator_main_loop(void);
void simulate_voice_interaction(void);
void simulate_posture_monitoring(void);
void simulate_hardware_control(void);
void save_data_record(void);
void print_system_status(void);
void print_help(void);
void handle_user_input(void);
int evaluate_posture(float distance);

/**
 * 主函数
 */
int main(void)
{
    printf("=== AIOT智能学习桌仿真测试 ===\n");
    printf("版本: %s\n", SYSTEM_VERSION);
    printf("设备名称: %s\n", DEVICE_NAME);
    printf("仿真模式: PC端测试\n\n");

    // 注册信号处理
    signal(SIGINT, signal_handler);

    // 初始化仿真环境
    simulator_init();

    // 显示帮助信息
    print_help();

    // 进入仿真主循环
    simulator_main_loop();

    return 0;
}

/**
 * 信号处理函数
 */
void signal_handler(int sig)
{
    if (sig == SIGINT)
    {
        printf("\n\n=== 系统正在关闭 ===\n");
        system_running = false;
    }
}

/**
 * 仿真初始化
 */
void simulator_init(void)
{
    DEBUG_PRINT(2, "初始化仿真环境...");

    // 初始化随机数种子
    srand(time(NULL));

    // 清空数据记录
    memset(data_records, 0, sizeof(data_records));
    record_index = 0;

    // 设置初始状态
    current_state = STATE_IDLE;
    simulated_distance = 40.0f + (rand() % 20 - 10); // 30-50cm随机

    DEBUG_PRINT(2, "仿真环境初始化完成");
    DEBUG_PRINT(2, "初始坐姿距离: %.1f cm", simulated_distance);
}

/**
 * 仿真主循环
 */
void simulator_main_loop(void)
{
    DEBUG_PRINT(2, "进入仿真主循环");

    int cycle_count = 0;

    while (system_running)
    {
        cycle_count++;

        // 模拟语音交互
        simulate_voice_interaction();

        // 模拟坐姿监测
        simulate_posture_monitoring();

        // 模拟硬件控制
        simulate_hardware_control();

        // 处理用户输入
        handle_user_input();

        // 每10个周期记录一次数据
        if (cycle_count % 10 == 0)
        {
            save_data_record();
        }

        // 每50个周期打印一次状态
        if (cycle_count % 50 == 0)
        {
            print_system_status();
        }

        // 模拟系统延时
        usleep(100000); // 100ms
    }

    printf("\n=== 仿真测试结束 ===\n");
    printf("总运行周期: %d\n", cycle_count);
    printf("数据记录条数: %d\n", record_index);
}

/**
 * 模拟语音交互
 */
void simulate_voice_interaction(void)
{
    static int voice_timer = 0;

    // 随机模拟语音检测
    if (rand() % 1000 < 5)
    { // 0.5% 概率检测到语音
        voice_detected = true;
        voice_timer = 30; // 持续3秒

        if (current_state == STATE_IDLE)
        {
            DEBUG_PRINT(2, "检测到唤醒词: 小助手");
            current_state = STATE_LISTENING;
            led_on = true;
        }
        else if (current_state == STATE_LISTENING)
        {
            // 随机选择问题类型
            int question_type = rand() % 3;
            switch (question_type)
            {
            case 0:
                DEBUG_PRINT(2, "语音识别: 什么时间了？");
                current_state = STATE_PROCESSING;
                break;
            case 1:
                DEBUG_PRINT(2, "语音识别: 开始口语练习");
                current_state = STATE_PRACTICE;
                break;
            case 2:
                DEBUG_PRINT(2, "语音识别: 音量调大一点");
                DEBUG_PRINT(2, "执行音量调节命令");
                break;
            }
        }
    }

    // 处理语音计时器
    if (voice_timer > 0)
    {
        voice_timer--;
        if (voice_timer == 0)
        {
            voice_detected = false;
        }
    }

    // 状态转换
    if (current_state == STATE_PROCESSING)
    {
        static int process_timer = 0;
        process_timer++;
        if (process_timer >= 30)
        { // 3秒处理时间
            DEBUG_PRINT(2, "AI回答: 现在是下午2点30分");
            current_state = STATE_SPEAKING;
            process_timer = 0;
        }
    }
    else if (current_state == STATE_SPEAKING)
    {
        static int speak_timer = 0;
        speak_timer++;
        if (speak_timer >= 20)
        { // 2秒播放时间
            DEBUG_PRINT(2, "语音播放完成");
            current_state = STATE_IDLE;
            led_on = false;
            speak_timer = 0;
        }
    }
    else if (current_state == STATE_PRACTICE)
    {
        static int practice_timer = 0;
        practice_timer++;
        if (practice_timer >= 100)
        { // 10秒练习时间
            DEBUG_PRINT(2, "口语练习完成，发音评分: 85分");
            current_state = STATE_IDLE;
            practice_timer = 0;
        }
    }
}

/**
 * 模拟坐姿监测
 */
void simulate_posture_monitoring(void)
{
    static int monitor_timer = 0;
    static int warning_count = 0;

    monitor_timer++;

    // 每1秒更新一次距离
    if (monitor_timer % 10 == 0)
    {
        // 模拟距离变化
        float change = (rand() % 10 - 5) * 0.5f; // -2.5 到 +2.5 cm
        simulated_distance += change;

        // 限制距离范围
        if (simulated_distance < 15.0f)
            simulated_distance = 15.0f;
        if (simulated_distance > 80.0f)
            simulated_distance = 80.0f;

        // 评估坐姿
        posture_score = evaluate_posture(simulated_distance);

        DEBUG_PRINT(3, "坐姿监测: 距离=%.1f cm, 评分=%d", simulated_distance, posture_score);

        // 检查是否需要警报
        if (posture_score < 60)
        {
            warning_count++;
            if (warning_count >= 3)
            {
                DEBUG_PRINT(2, "坐姿不良警报！距离: %.1f cm", simulated_distance);
                buzzer_on = true;

                // 语音提示
                if (current_state == STATE_IDLE)
                {
                    DEBUG_PRINT(2, "语音提示: 请调整坐姿，保持适当距离");
                }

                warning_count = 0;
            }
        }
        else
        {
            warning_count = 0;
            buzzer_on = false;
        }
    }
}

/**
 * 模拟硬件控制
 */
void simulate_hardware_control(void)
{
    static bool prev_led_state = false;
    static bool prev_buzzer_state = false;

    // LED状态变化
    if (led_on != prev_led_state)
    {
        printf("💡 LED: %s\n", led_on ? "🟢 开启" : "⚫ 关闭");
        prev_led_state = led_on;
    }

    // 蜂鸣器状态变化
    if (buzzer_on != prev_buzzer_state)
    {
        printf("🔊 蜂鸣器: %s\n", buzzer_on ? "🔴 警报" : "⚫ 关闭");
        prev_buzzer_state = buzzer_on;
    }
}

/**
 * 处理用户输入
 */
void handle_user_input(void)
{
    // 非阻塞输入检查（简化实现）
    // 实际应用中可以使用select()或其他方法
}

/**
 * 评估坐姿
 */
int evaluate_posture(float distance)
{
    int score = 100;

    // 理想距离：30-50cm
    if (distance >= 30.0f && distance <= 50.0f)
    {
        score = 100;
    }
    // 警告距离：20-30cm 或 50-70cm
    else if ((distance >= 20.0f && distance < 30.0f) ||
             (distance > 50.0f && distance <= 70.0f))
    {
        score = 70;
    }
    // 危险距离：<20cm 或 >70cm
    else if (distance < 20.0f || distance > 70.0f)
    {
        score = 30;
    }

    return score;
}

/**
 * 保存数据记录
 */
void save_data_record(void)
{
    if (record_index >= MAX_RECORDS)
    {
        record_index = 0; // 循环覆盖
    }

    data_record_t *record = &data_records[record_index];
    record->timestamp = time(NULL);
    record->distance = simulated_distance;
    record->posture_score = posture_score;
    record->voice_detected = voice_detected;
    record->state = current_state;

    record_index++;
}

/**
 * 打印系统状态
 */
void print_system_status(void)
{
    printf("\n=== 系统状态报告 ===\n");
    printf("当前状态: %s\n",
           current_state == STATE_IDLE ? "空闲" : current_state == STATE_LISTENING ? "监听中"
                                              : current_state == STATE_PROCESSING  ? "处理中"
                                              : current_state == STATE_SPEAKING    ? "播放中"
                                              : current_state == STATE_PRACTICE    ? "练习中"
                                                                                   : "错误");
    printf("坐姿距离: %.1f cm\n", simulated_distance);
    printf("坐姿评分: %d 分\n", posture_score);
    printf("语音检测: %s\n", voice_detected ? "是" : "否");
    printf("LED状态: %s\n", led_on ? "开启" : "关闭");
    printf("蜂鸣器: %s\n", buzzer_on ? "警报" : "关闭");
    printf("数据记录: %d/%d\n", record_index, MAX_RECORDS);
    printf("=====================\n\n");
}

/**
 * 打印帮助信息
 */
void print_help(void)
{
    printf("=== 仿真测试说明 ===\n");
    printf("本程序模拟EBP3901开发板上的智能学习桌系统\n");
    printf("\n仿真功能:\n");
    printf("1. 🎤 语音交互 - 随机触发语音识别和AI回答\n");
    printf("2. 📏 坐姿监测 - 模拟距离变化和坐姿评估\n");
    printf("3. 💡 硬件控制 - LED和蜂鸣器状态显示\n");
    printf("4. 📊 数据记录 - 记录系统运行数据\n");
    printf("\n操作说明:\n");
    printf("- 程序自动运行，无需手动操作\n");
    printf("- 按 Ctrl+C 退出仿真\n");
    printf("- 观察控制台输出了解系统状态\n");
    printf("========================\n\n");

    printf("�� 仿真测试开始...\n\n");
}